package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public Result queryTypeList() {
        //查询redis
        List<String> shopTypeJson = stringRedisTemplate.opsForList().range("shop:type:", 0, -1);
        //存在，直接返回
        if (shopTypeJson != null && !shopTypeJson.isEmpty()){
            List<ShopType> shopTypes = shopTypeJson.stream()
                    .map(jsonStr -> {
                        try {
                            // 将JSON字符串反序列化为ShopType对象
                            return objectMapper.readValue(jsonStr, ShopType.class);
                        } catch (JsonProcessingException e) {
                            throw new RuntimeException("Redis数据反序列化失败", e);
                        }
                    })
                    .collect(Collectors.toList());
            return Result.ok(shopTypes);
        }
        //不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //不存在，返回
        if (typeList == null || typeList.isEmpty()){
            return Result.fail("店铺类型不存在");
        }
        List<String> jsonStrings = typeList.stream()
                .map(shopType -> {
                    try {
                        // 将ShopType对象序列化为JSON字符串
                        return objectMapper.writeValueAsString(shopType);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException("ShopType序列化失败", e);
                    }
                })
                .collect(Collectors.toList());
        //存在，写入redis
        stringRedisTemplate.opsForList().rightPushAll("shop:type:",jsonStrings);
        // 返回
        return Result.ok(typeList);
    }
}
